package kr.co.sdworld.api.apns.service;

import java.util.List;

import kr.co.sdworld.api.apns.model.ApnsApp;
import kr.co.sdworld.api.apns.model.ApnsLogin;
import kr.co.sdworld.api.apns.model.base.Model;
import kr.co.sdworld.api.apns.repository.WhereCondition;
import kr.co.sdworld.api.apns.repository.WhereCondition.Operation;
import kr.co.sdworld.api.apns.repository.WhereCondition.OrderType;
import kr.co.sdworld.api.apns.repository.app.ApnsAppDao;
import kr.co.sdworld.api.apns.service.base.ListResult;
import kr.co.sdworld.stone.ListParam;
import kr.co.sdworld.stone.Pager;
import kr.co.sdworld.stone.SpringBeanUtil;
import kr.co.sdworld.webs.ServiceContext;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AppServiceImpl implements AppService
{
	@Override
	public ListResult getApnsAppList( ListParam param)
	{
		ApnsLogin login = (ApnsLogin) ServiceContext.getSession().getAttribute( "login");

		WhereCondition whereCondition = new WhereCondition();
		whereCondition.addCondition( "user_id", login.getUserId(), Operation.OPT_EQUAL);
		whereCondition.addOrder( "reg_dt", OrderType.ASC);

		int totalCount = SpringBeanUtil.repository( ApnsAppDao.class).searchCount( whereCondition);

		Pager pager = Pager.makePager( totalCount, param.getPageNum(), param.getMaxRow());
		List<Model> list = SpringBeanUtil.repository( ApnsAppDao.class).search( pager.getStartNum(), pager.getEndNum(), whereCondition);

		ListResult result = new ListResult();
		result.setList( list);
		result.setTotalCount( totalCount);

		return result;
	}

	@Override
	public ApnsApp saveApp( String appId, String appName, String appDesc)
	{
		ApnsLogin login = (ApnsLogin) ServiceContext.getSession().getAttribute( "login");
		String userId = login.getUserId();
		ApnsApp apnsApp = new ApnsApp();
		apnsApp.setAppId( appId);
		apnsApp.setAppName( appName);
		apnsApp.setAppDesc( appDesc);
		apnsApp.setUserId( userId);

		int result = SpringBeanUtil.repository( ApnsAppDao.class).create( apnsApp);
		if ( result > 0)
		{
			return SpringBeanUtil.repository( ApnsAppDao.class).getApnsApp( appId);
		}
		return null;
	}

	@Override
	@Transactional
	public void deleteApp( String[] appIdArray)
	{
		for ( String appId : appIdArray)
		{
			SpringBeanUtil.repository( ApnsAppDao.class).delete( appId);
		}
	}

	@Override
	public void deleteApp( String appId)
	{
		SpringBeanUtil.repository( ApnsAppDao.class).delete( appId);
	}
}
